#include "greatarr1.h"
#include "status.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//char str[]="(((a,b,c),(d)),e)";
//char str[]="(a,b,c)";
void decomposestr(char str[],char hstr[]){
	int i,j,tag,n=strlen(str);
	char ch;
	ch=str[0];
	tag=0;
	for(i=0;i<=n-1;i++){
		if(str[i]==',' && tag==1)
			break;
		ch=str[i];
		if(ch=='(')tag++;
		if(ch==')')tag--;
	}
	if(i<=n-1 && str[i]==','){
		for(j=0;j<i-1;j++)
			hstr[j]=str[j+1];
		hstr[j]='\0';
		if(str[i]==',')i++;
		str[0]='(';
		for(j=1;i<=n-2;i++,j++)
			str[j]=str[i];
		str[j]=')';
		str[++j]='\0';
	}else{
		str++;
		strncpy(hstr,str,n-2);
		hstr[n-2]='\0';
		str--;
		strcpy(str,"()");
	}
}
status init(glnode **s,char str[]){
	int len=strlen(str);
	if(strcmp("()",str)==0){ 
		*s=NULL;
	}else if(len==1){
		glnode *h=(glnode*)malloc(sizeof(glnode));
		if(!h)exit(overflow);
		h->tag=0;
		h->val.atom=str[0];
		*s=h;
		return ok;
	}else{
		glnode *h=(glnode*)malloc(sizeof(glnode));
		h->tag=1;
		char hstr[200];
		decomposestr(str,hstr);
		glnode *head;
		init(&head,hstr);
		h->val.sublist.head=head;
		glnode *tail;
		init(&tail,str);
		h->val.sublist.tail=tail;
		*s=h;
		return ok;
	}
}

status length(glnode *s){
	int num=0;
	glnode *p;
	for(p=s;p!=NULL;p=p->val.sublist.tail){
		num++;
	}
	return num;
}

status atomnum(glnode *s){
	glnode *h;
	h=s;
	if(h){
		if(h->tag==0)return 1;
		else
			return atomnum(h->val.sublist.head)+
				atomnum(h->val.sublist.tail);
	}else{
		return 0;
	}
}

status depth(glnode *s){
	int max,dep;
	glnode *pre;
	if(s==NULL)return 1;
	if(s->tag==0)return 0;
	pre=s;
	for(max=0;pre !=NULL ;pre=pre->val.sublist.tail){
		dep=length(pre->val.sublist.head);
		if(dep>max)max=dep;
	}
	return max+1;
}

status gethead(glnode *s,glnode **head){
	if(s){
		if(s->tag==0)
			*head=s;
		else
			*head=s->val.sublist.head;
		return ok;
	}
	return ok;
}
status gettail(glnode *s,glnode **tail){
	if(s){
		if(s->tag==0)
			*tail=s;
		else
			*tail=s->val.sublist.tail;
		return ok;
	}
	return ok;
}
status search(glnode *s){
}

status insert(glnode *s,datatype e){
}

status destroy(glnode *s){
	if(s==NULL){
		return ok;
	}else{
		if(s->tag && s->val.sublist.head) destroy(s->val.sublist.head);
		if(s->tag && s->val.sublist.tail) destroy(s->val.sublist.tail);
		free(s);
	}
}

void show(glnode *s){
	if(s==NULL){
		return;
	}
	glnode *p;
	p=s;
	if(p->tag==0){
		printf("%c ",p->val.atom);
	}else{
		show(p->val.sublist.head);
		show(p->val.sublist.tail);
		printf("\n");
	}
}
int main(){
	char str[]="(((a,b,c),(d)),e)";
	//char str[]="(a,b,c)";
	glnode *h;
	init(&h,str);
	show(h);
	printf("%d\n",depth(h));
	printf("%d\n",length(h));
	printf("%d\n",atomnum(h));
	printf("start head:\n");
	glnode *head,*tail;
	gethead(h,&head);
	gettail(h,&tail);
	show(head);
	printf("start show tail:\n");
	show(tail);
	destroy(h);
}

